<template>
  <el-card class="page_card">
    <div class="left_con">
      <el-input v-model="data.filterText" placeholder="请输入关键字搜索" />
      <el-tree 
        ref="treeRef" 
        highlight-current 
        default-expand-all 
        :data="data.categoryTreeData" 
        node-key="id"
        :props="data.defaultProps" 
        :filter-node-method="filterNode"
        :current-node-key="data.currentNodeKey"
        @node-click="handleNodeClick"/>
    </div>
    <div class="right_con">
      <el-form :inline="true" class="form">
        <el-form-item label="姓名：">
          <el-input v-model="data.keyword" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" color="#626aef" @click="search"
            :disabled="data.keyword ? false : true">搜索</el-button>
          <el-button @click="reset" color="#626aef" plain>重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" icon="Plus" @click="addCase" :disabled="data.isAddCaseBtn">添加病例</el-button>
      <el-table border :data="data.caseTableData" row-key="id">
        <el-table-column label="#" align="center" type="index" :width="60"></el-table-column>
        <el-table-column label="姓名" align="center" prop="name"></el-table-column>
        <el-table-column label="性别" align="center" prop="gender"></el-table-column>
        <el-table-column label="年龄" align="center" prop="age"></el-table-column>
        <el-table-column label="籍贯" align="center" prop="nativePlace"></el-table-column>
        <el-table-column label="民族" align="center" prop="nationality"></el-table-column>
        <el-table-column label="职业" align="center" prop="career"></el-table-column>
        <el-table-column label="文化程度" align="center" prop="education"></el-table-column>
        <el-table-column label="操作" width="220px" align="center">
          <template #="{ row }">
            <el-button type="primary" link icon="View" @click="viewOrUpdateCase(row,true)">查看</el-button>
            <el-button type="primary" link icon="Edit" @click="viewOrUpdateCase(row,false)">编辑</el-button>
            <el-popconfirm :title="`确认删除${row.name}吗？`" width="240px" @confirm="deleteCase(row)">
              <template #reference>
                <el-button type="danger" link icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="->,prev, pager, next, jumper,sizes,total"
        :total="data.total"
        @current-change="currentChange"
        @size-change="sizeChange"
      />
    </div>
  </el-card>
  <!-- 添加病例、更新病例 -->
  <el-dialog v-model="data.addCaseDialog" :title="data.basicInfoForm.id ? '更新病例' : '添加病例'" width="1200">
    <el-tabs v-model="data.activeName" class="demo-tabs" @tab-click="tabClick">
      <el-tab-pane label="基本信息" name="1">
        <el-form :model="data.basicInfoForm" :rules="data.rules" ref="formRef" label-width="150px" class="add_form_con">
          <div class="left_form">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="data.basicInfoForm.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="data.basicInfoForm.gender">
                <el-radio value="男">男</el-radio>
                <el-radio value="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="data.basicInfoForm.age" :min="1" placeholder="请输入年龄"></el-input-number>
            </el-form-item>
            <el-form-item label="籍贯" prop="nativePlace">
              <el-input v-model="data.basicInfoForm.nativePlace" placeholder="请输入籍贯"></el-input>
            </el-form-item>
            <el-form-item label="民族" prop="nationality">
              <el-input v-model="data.basicInfoForm.nationality" placeholder="请输入民族"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="file">
              <el-upload
                class="avatar_uploader"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleChange">
                <img v-if="data.fileImg" :src="data.fileImg" class="avatar" />
                <el-icon v-else class="avatar_uploader_icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </div>
          <div class="right_form">
            <el-form-item label="职业" prop="career">
              <el-input v-model="data.basicInfoForm.career" placeholder="请输入职业"></el-input>
            </el-form-item>
            <el-form-item label="文化程度" prop="education">
              <el-input v-model="data.basicInfoForm.education" placeholder="请选择文化程度"></el-input>
            </el-form-item>
            <el-form-item label="家庭住址" prop="address">
              <el-input v-model="data.basicInfoForm.address" placeholder="请输入家庭住址"></el-input>
            </el-form-item>
            <el-form-item label="机构名称" prop="parentNodeName">
              <el-input v-model="data.basicInfoForm.parentNodeName" disabled></el-input>
            </el-form-item>
            <el-form-item label="类别" prop="categoryName">
              <el-input v-model="data.basicInfoForm.categoryName" disabled></el-input>
            </el-form-item>
            <!-- <el-form-item label="背景音乐" prop="bgMusic">
              <el-upload
                ref="upload"
                class="upload_demo"
                action="#"
                :limit="1"
                :on-exceed="handleExceed"
                :auto-upload="false">
                <template #trigger>
                  <el-button type="primary" icon="Upload" round size="small">上传文件</el-button>
                </template>
              </el-upload>
            </el-form-item> -->
          </div>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="导医对话" name="2">
        <el-button type="primary" icon="Plus" @click="addQuestion" :disabled="data.addFlag">添加对话</el-button>
        <el-table border :data="data.dialogueTableData" row-key="id" max-height="500">
          <el-table-column label="#" align="center" type="index" :width="60"></el-table-column>
          <el-table-column label="问题" align="center" prop="question" show-overflow-tooltip></el-table-column>
          <el-table-column label="答案" align="center" prop="answer" show-overflow-tooltip></el-table-column>
          <el-table-column label="分值" align="center" prop="score" width="90"></el-table-column>
          <el-table-column label="是否必问" align="center" prop="required" width="90">
            <template #="{ row }">
              <el-checkbox v-model="row.required" :true-value="1" :false-value="0" @change="checkboxChange(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220px" align="center">
            <template #="{ row }">
              <el-button type="primary" link icon="View" @click="viewOrUpdateQuestion(row,true)">查看</el-button>
              <el-button type="primary" link icon="Edit" @click="viewOrUpdateQuestion(row,false)">编辑</el-button>
              <el-popconfirm :title="`确认删除${row.question}吗？`" width="240px" @confirm="deleteQuestion(row)">
                <template #reference>
                  <el-button type="danger" link icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="问诊" name="3">
        <el-button type="primary" icon="Plus" @click="addQuestion" :disabled="data.addFlag">添加问诊</el-button>
        <el-table border :data="data.questionTableData" row-key="id" max-height="500">
          <el-table-column label="#" align="center" type="index" :width="60"></el-table-column>
          <el-table-column label="问题" align="center" prop="question" show-overflow-tooltip></el-table-column>
          <el-table-column label="答案" align="center" prop="answer" show-overflow-tooltip></el-table-column>
          <el-table-column label="分值" align="center" prop="score" width="90"></el-table-column>
          <el-table-column label="问题类型" align="center" prop="questionType" width="100"></el-table-column>
          <el-table-column label="是否必问" align="center" prop="required" width="90">
            <template #="{ row }">
              <el-checkbox v-model="row.required" :true-value="1" :false-value="0" @change="checkboxChange(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220px" align="center">
            <template #="{ row }">
              <el-button type="primary" link icon="View" @click="viewOrUpdateQuestion(row,true)">查看</el-button>
              <el-button type="primary" link icon="Edit" @click="viewOrUpdateQuestion(row,false)">编辑</el-button>
              <el-popconfirm :title="`确认删除${row.question}吗？`" width="240px" @confirm="deleteQuestion(row)">
                <template #reference>
                  <el-button type="danger" link icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div class="dialog-footer" v-if="data.activeName=='1'">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save" :disabled="data.saveCaseDisabled">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加问诊/添加导医对话 -->
  <el-dialog v-model="data.addQuestionDialog" :title="data.questionForm.id ? '更新问题' : '添加问题'" width="700" :align-center="true">
    <el-form :model="data.questionForm" :rules="data.rules" ref="questionFormRef" label-width="120px" style="max-width: 600px">
      <el-form-item label="问题类型" prop="questionType" v-if="data.activeName=='3'">
        <el-select v-model="data.questionForm.questionType" placeholder="请选择问题类型" >
          <el-option label="一般问题" value="一般问题"/>
          <el-option label="业务问题" value="业务问题"/>
        </el-select>
      </el-form-item>
      <el-form-item label="问题" prop="question">
        <el-input v-model="data.questionForm.question" placeholder="请输入问题" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="答案" prop="answer">
        <el-input v-model="data.questionForm.answer" placeholder="请输入答案" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="分值" prop="score">
        <el-input-number v-model="data.questionForm.score" placeholder="请输入分值" style="width:480px"></el-input-number>
      </el-form-item>
      <el-form-item label="是否必问" prop="required">
        <el-checkbox v-model="data.questionForm.required" :true-value="1" :false-value="0"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.addQuestionDialog = false">取消</el-button>
        <el-button type="primary" @click="saveQuestion" :disabled="data.saveBtnDisabled">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick, watch, onUnmounted } from 'vue'
import { reqCategoryTree,reqGetDataByCategoryCode,reqAddOrUpdateCase,reqRemoveCase,
  reqGetQuestionDataByCaseInfoId,reqAddOrUpdateQuestion,reqRemoveQuestion} from '@/api/case/caseApi'
import type { Case, } from '@/api/case/caseType'
import { ElMessage } from 'element-plus'
import useLayOutSettingStore from '@/store/modules/setting'
import { ElTree } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { reqGetImg } from '@/api/file/index'
import { blobToUrl } from '@/utils/file'

const upload = ref<UploadInstance>()
let settingStore = useLayOutSettingStore() // 模板setting仓库
let formRef = ref<any>() //form表单实例
let questionFormRef = ref<any>() //form表单实例
const treeRef = ref<InstanceType<typeof ElTree>>()
const data = reactive({
  filterText: '',
  categoryTreeData: [] as Array<any>, //类别树
  currentNodeKey: '', //当前选中节点id
  currentNodeName:'', //当前选择节点name
  currentParentNodeName:'', //当前选中节点父节点name
  keyword: '',
  currentPage:1,
  pageSize:10,
  total:0,
  caseTableData: [] as Case[], //基本信息表格
  addCaseDialog: false, //新增对话框
  basicInfoForm: { //新增表单
    parentNodeName:'', //选中类别父节点name
    categoryName:'', //选中类别name
    categoryId:'', //选中类别id
    name: '',
    gender: '男',
    age: null || '',
    nativePlace: '',
    nationality: '',
    career: '',
    education: '',
    address: '',
    avatar: '',
    bgMusic:'',
    file:'',
    id: '',
    version:'',
  },
  activeName:'1',
  addQuestionDialog:false,
  questionTableData: [] as Array<any>, //问诊表格
  questionForm:{
    caseInfoId:'', //当前病例id
    questionType:'一般问题',
    question:'',
    answer:'',
    score:null,
    required:1,
    id:'',
    scene:'', //0是导医，1是问诊
  },
  defaultProps:{
    children: 'children',
    label: 'name',
  },
  rules:{
    name: [{ required: true, trigger: 'blur', message: '请输入姓名' }],
    gender: [{ required: true, trigger: 'blur', message: '请选择性别' }],
    age: [{ required: true, trigger: 'blur', message: '请输入年龄' }],
    nativePlace: [{ required: true, trigger: 'blur', message: '请输入籍贯' }],
    nationality: [{ required: true, trigger: 'blur', message: '请输入民族' }],
    career: [{ required: true, trigger: 'blur', message: '请输入职业' }],
    education: [{ required: true, trigger: 'blur', message: '请输入文化程度' }],
    questionType: [{ required: true, trigger: 'blur', message: '请选择问题类型' }],
    question: [{ required: true, trigger: 'blur', message: '请输入问题' }],
    answer: [{ required: true, trigger: 'blur', message: '请输入答案' }],
    score: [{ required: true, trigger: 'blur', message: '请输入分值' }],
  },
  isAddCaseBtn:true, //是否选中类别子节点
  saveCaseDisabled:false,
  saveBtnDisabled:false,
  fileImg:'', //上传图片后回显
  addFlag:false, //新增问诊按钮是否禁用
  dialogueTableData: [] as Array<any>, //导医对话表格
})

onMounted(() => {
  initTreeData()
})

watch( ()=> data.filterText, (val)=> {
  treeRef.value!.filter(val)
}
)

// 复选框勾选事件
const checkboxChange = async (row:any) => {
  let res = await reqAddOrUpdateQuestion(row)
  if (res.code == 200) {
    data.addQuestionDialog = false
    ElMessage.success('更新成功！')
    getQuestionDataByCaseInfoId()
  } else {
    data.addQuestionDialog = false
    ElMessage.error('更新失败！')
  }
}
// 树节点搜索
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.includes(value)
}
// 根据病例caseInfoId查询问诊数据
const getQuestionDataByCaseInfoId = async (caseInfoId=data.basicInfoForm.id) => {
  let res: any = await reqGetQuestionDataByCaseInfoId(caseInfoId)
  if(res.code==200){
    data.questionTableData = res.data.filter((item:any) => item.scene==1)
    data.dialogueTableData = res.data.filter((item:any) => item.scene==0)
  }
}
// 添加问诊 / 添加导医对话
const addQuestion = () => {
  data.addQuestionDialog = true
  // 清空数据
  Object.assign(data.questionForm, {
    caseInfoId:data.basicInfoForm.id, //当前病例id
    questionType:'一般问题',
    question:'',
    answer:'',
    score:null,
    required:1,
    id:'',
    scene:'', //0是导医，1是问诊
  })
  nextTick(() => {
    // 清除上一次错误提示信息
    questionFormRef.value.clearValidate('questionType')
    questionFormRef.value.clearValidate('question')
    questionFormRef.value.clearValidate('answer')
    questionFormRef.value.clearValidate('score')
  })
}
// 查看编辑问诊
const viewOrUpdateQuestion = (row:any,disabled:boolean) => {
  data.saveBtnDisabled = disabled
  data.addQuestionDialog = true
  Object.assign(data.questionForm, row)
  nextTick(() => {
    // 清除上一次错误提示信息
    questionFormRef.value.clearValidate('questionType')
    questionFormRef.value.clearValidate('question')
    questionFormRef.value.clearValidate('answer')
    questionFormRef.value.clearValidate('score')
  })
}
// 保存问诊
const saveQuestion = async () => {
  try {
    await questionFormRef.value.validate()
    let saveParam = JSON.parse(JSON.stringify(data.questionForm))
    saveParam.scene = data.activeName=='2'?0:data.activeName=='3'?1:'' //0是导医，1是问诊
    let res = await reqAddOrUpdateQuestion(saveParam)
    if (res.code == 200) {
      data.addQuestionDialog = false
      ElMessage.success(data.questionForm.id ? '更新成功！' : '添加成功！')
      getQuestionDataByCaseInfoId()
    } else {
      data.addQuestionDialog = false
      ElMessage.error(data.questionForm.id ? '更新失败！' : '添加失败！')
    }
  } catch (error) { }
}
// 删除单个问诊
const deleteQuestion = async (row:any) => {
  let res = await reqRemoveQuestion((row.id as number), row.version)
  if (res.code == 200) {
    ElMessage.success('删除成功！')
    getQuestionDataByCaseInfoId()
  } else {
    ElMessage.error('删除失败！')
  }
}
// 图片上传
const handleChange = (file:any) => {
  data.basicInfoForm.file = file.raw //FormData格式图片
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = (e) => {
    data.fileImg = (e.target?.result as string)
  }
}
// 背景音乐 文件上传
// const handleExceed: UploadProps['onExceed'] = (files) => {
//   upload.value!.clearFiles()
//   const file = files[0] as UploadRawFile
//   file.uid = genFileId()
//   upload.value!.handleStart(file)
// }

// tab页切换
// @ts-ignore
const tabClick = (tab: TabsPaneContext, event: Event) => {
  data.activeName = (tab.props.name as string)
  getQuestionDataByCaseInfoId()
}

// 类别树
const initTreeData = async () => {
  let res: any = await reqCategoryTree()
  if(res.code==200){
    data.categoryTreeData = res.data
    if(res.data.length==0 || res.data[0].children.length==0){
      data.isAddCaseBtn = true
      return
    }
    // 子节点默认勾选第一个
    data.isAddCaseBtn = false
    data.currentNodeKey = res.data[0]?.children[0]?.id
    data.currentNodeName = res.data[0]?.children[0]?.name
    data.currentParentNodeName = getParentNodeName(res.data[0]?.children[0]?.parentId)
    nextTick(() => {
      treeRef.value?.setCurrentKey(data.currentNodeKey)
      initTableData(data.currentNodeKey)
    })
  }
}
// 搜索
const search = () => {
  initTableData()
}
// 重置
const reset = () => {
  settingStore.refsh = !settingStore.refsh
}
// 分页器下拉事件
const currentChange = () => {
  initTableData(data.currentNodeKey,data.currentPage)
}
const sizeChange = ()=> {
  initTableData()
}
// 点击树节点查询表格数据
const handleNodeClick = (nodeData: any) => {
  if(nodeData.parentId != 0){
    data.isAddCaseBtn = false
    data.currentNodeKey = nodeData.id
    data.currentNodeName = nodeData.name
    data.currentParentNodeName = getParentNodeName(nodeData.parentId)
    initTableData(data.currentNodeKey)
  }else{
    data.isAddCaseBtn = true
  }
}
// 根据子节点id查询父节点名称
const getParentNodeName = (id:number) => {
  return data.categoryTreeData.find(item => item.id==id).name
}
// 根据类别categoryId查询信息表格数据
const initTableData = async (categoryId=data.currentNodeKey,pager=1) => {
  data.currentPage = pager
  let params = {
    current:data.currentPage,
    size:data.pageSize,
    categoryId:categoryId,
    name:data.keyword
  }
  let res: any = await reqGetDataByCategoryCode(params)
  if(res.code==200){
    data.caseTableData = res.data.records
    data.total = res.data.total
  }
}

// 新增对话框
const addCase = () => {
  data.addFlag = true
  data.activeName = '1'
  data.addCaseDialog = true
  // 清空数据
  data.fileImg = ''
  Object.assign(data.basicInfoForm, {
    parentNodeName:data.currentParentNodeName, //选中类别父节点name
    categoryName:data.currentNodeName, //选中类别name
    categoryId:data.currentNodeKey, //选中类别id
    name: '',
    gender: '男',
    age: null,
    nativePlace: '',
    nationality: '',
    career: '',
    education: '',
    address: '',
    avatar: '',
    bgMusic:'',
    file:'',
    id: '',
    version:'',
  })
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('gender')
    formRef.value.clearValidate('age')
    formRef.value.clearValidate('nativePlace')
    formRef.value.clearValidate('nationality')
    formRef.value.clearValidate('career')
    formRef.value.clearValidate('education')
  })
}

onUnmounted(() => {
  if (data.fileImg) {  
    URL.revokeObjectURL(data.fileImg)
  } 
})

// 查看/编辑对话框
const viewOrUpdateCase = async (row:Case,disabled:boolean) => {
  data.addFlag = false
  data.fileImg = ''
  // 根据文件名获取图片数据回显img
  let res = await reqGetImg(row.avatar)
  if (res) {
    // blob转url
    blobToUrl(res).then(dataUrl => {  
      data.fileImg = dataUrl
    }).catch(error => {ElMessage.error(error)})
  }
  data.saveCaseDisabled = disabled
  data.activeName = '1'
  data.addCaseDialog = true
  Object.assign(data.basicInfoForm, row)
  data.basicInfoForm.parentNodeName = data.currentParentNodeName
  data.basicInfoForm.categoryName = data.currentNodeName
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('gender')
    formRef.value.clearValidate('age')
    formRef.value.clearValidate('nativePlace')
    formRef.value.clearValidate('nationality')
    formRef.value.clearValidate('career')
    formRef.value.clearValidate('education')
  })
}
// 新增/编辑确认
const save = async () => {
  try {
    await formRef.value.validate()
    const formData = new FormData()
    const {file,id,categoryId,name,gender,age,nativePlace,nationality,career,education,address,bgMusic,version} = data.basicInfoForm
    const staticFields = {id,categoryId,name,gender,age,nativePlace,nationality,career,education,address,bgMusic,version}
    for(const [key, value] of Object.entries(staticFields)) {  
      formData.append(key, value)
    }
    if(file) {  
      formData.append('file', file) //上传文件处理
    }
    let res = await reqAddOrUpdateCase(formData)
    if (res.code == 200) {
      data.addCaseDialog = false
      ElMessage.success(data.basicInfoForm.id ? '更新成功！' : '添加成功！')
      initTableData()
    } else {
      data.addCaseDialog = false
      ElMessage.error(res.msg)
    }
  } catch (error) { }
}
// 关闭 基本信息对话框
const cancel = () => {
  data.addCaseDialog = false
}

// 删除单行病例
const deleteCase = async (row: Case) => {
  let res = await reqRemoveCase((row.id as number), row.version)
  if (res.code == 200) {
    ElMessage.success('删除成功！')
    initTableData()
  } else {
    ElMessage.error('删除失败！')
  }
}
</script>

<style scoped lang="scss">
:deep(.el-card__body) {
  display: flex;
  height: 100%;
  .left_con {
    width: 260px;
    height: 100%;
    border-right: 1px solid #dcdfe6;
    padding-right: 20px;
    .el-tree {
      margin-top: 14px;
    }
  }
  .right_con {
    flex: 1;
    height: 100%;
    padding-left: 20px;
  }
}
.add_form_con{
  display: flex;
  margin-top: 20px;
  .el-input,.el-input-number{
    width: 320px;
  }
}
.avatar_uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<style>
.avatar_uploader .el-upload {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar_uploader .el-upload:hover {
  border-color: #626aef;
}
.el-icon.avatar_uploader_icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px !important;
  height: 120px !important;
  text-align: center;
}
</style>
